package com.example.singleactivitytemplate.ui.fragment.setting

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import com.example.singleactivitytemplate.R
import com.example.singleactivitytemplate.databinding.FragmentSettingBinding
import com.example.singleactivitytemplate.ui.base.BaseFragment


class SettingFragment : BaseFragment<FragmentSettingBinding, SettingViewModel>(),
    View.OnClickListener,View.OnLongClickListener {
    private var navHostController: NavController? = null
    override fun getViewBindingClass(
        inflater: LayoutInflater, container: ViewGroup?
    ): FragmentSettingBinding {
        return FragmentSettingBinding.inflate(inflater, container, false)
    }

    override fun getViewModelClass(): Class<SettingViewModel> {
        return SettingViewModel::class.java
    }

    override fun initData() {
        //设置主界面
        val navHostFragment =
            childFragmentManager.findFragmentById(R.id.setting_navigation) as NavHostFragment?
        navHostController = navHostFragment?.navController
    }

    override fun initOnListener() {
        viewBinding?.btnDeviceInfo?.setOnClickListener(this)
        viewBinding?.btnBasicSettings?.setOnClickListener(this)
        viewBinding?.btnLanguageSwitch?.setOnClickListener(this)
        viewBinding?.btnDeviceInfo?.setOnLongClickListener(this)
    }

    override fun initObserver() {
        mViewModel?.mFragmentId?.observe(this) {
            switchFragment(it)
        }
        mViewModel?.selectSettingTag?.observe(this) {
            val viewList = listOf(
                viewBinding?.btnBasicSettings,
                viewBinding?.btnLanguageSwitch,
                viewBinding?.btnDeviceInfo,
            )
            for (view in viewList) {
                view?.isSelected = false
            }
            when (it) {
                1 -> {
                    viewBinding?.btnBasicSettings?.isSelected = true
                }
                2 -> {
                    viewBinding?.btnLanguageSwitch?.isSelected = true
                }
                3 -> {
                    viewBinding?.btnDeviceInfo?.isSelected = true
                }
            }
        }
    }

    /**
     * 切换Fragment
     * @param fragmentId 目标Fragment的Id
     */
    private fun switchFragment(fragmentId: Int) {
        if (navHostController?.popBackStack(fragmentId, false) == false) {
            val builder = NavOptions.Builder().apply {}
            builder.setLaunchSingleTop(true)
            navHostController?.navigate(fragmentId, null, builder.build())
        }
    }


    override fun onClick(v: View?) {

    }
    override fun onLongClick(v: View?): Boolean {

        return true
    }
    override fun detach() {
    }


}